<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :model="searchForm" inline :label-width="100" class="search-form">
          <Form-item label="代理商名称" prop="username">
            <Input type="text" v-model="searchForm.username" placeholder="请输入会员名称" clearable style="width: 200px" />
          </Form-item>

          <Form-item label="代理商昵称" prop="nickName">
            <Input type="text" v-model="searchForm.nickName" placeholder="请输入会员昵称" clearable style="width: 200px" />
          </Form-item>

          <Form-item label="联系方式" prop="mobile">
            <Input type="text" v-model="searchForm.mobile" placeholder="请输入会员联系方式" clearable style="width: 200px" />
          </Form-item>
          <Button @click="handleSearch" class="search-btn" type="primary" icon="ios-search">搜索</Button>
        </Form>
      </Row>
      <!--   <Row class="operation padding-row" v-if="!selectedMember">
        <Button @click="addMember" type="primary">添加会员</Button>
      </Row> -->

      <Table :loading="loading" border :columns="columns" class="mt_10" :data="data" ref="table"></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage"
          @on-page-size-change="changePageSize" :page-size-opts="[10, 20, 50, 100]" size="small" show-total
          show-elevator show-sizer></Page>
      </Row>
    </Card>

    <!-- 添加用户模态框 -->
    <Modal v-model="addFlag" title="添加会员">
      <Form ref="addMemberForm" :model="addMemberForm" :rules="addRule" :label-width="100">
        <FormItem label="手机号码" prop="mobile" style="width: 90%;">
          <Input v-model="addMemberForm.mobile" maxlength="11" placeholder="请输入手机号码" />
        </FormItem>
        <FormItem label="会员名称" prop="username" style="width: 90%">
          <Input v-model="addMemberForm.username" maxlength="15" placeholder="请输入会员名称" />
        </FormItem>

        <FormItem label="会员密码" prop="password" style="width: 90%">
          <Input type="password" password v-model="addMemberForm.password" maxlength="20" placeholder="请输入会员密码" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="addFlag = false">取消</Button>
        <Button type="primary" @click="addMemberSubmit">确定</Button>
      </div>
    </Modal>
    <!-- 修改模态框 -->
    <Modal v-model="descFlag" :title="descTitle" @on-ok="handleSubmitModal" width="500">
      <Form ref="form" :model="form" :rules="ruleValidate" :label-width="80">
        <FormItem label="所在地" prop="mail">
          <div class="form-item">
            <region style="width: 250px" @selected="selectedRegion" />
          </div>
        </FormItem>
      </Form>
    </Modal>
    <Modal width="1200px" v-model="picModelFlag">
      <ossManage @callback="callbackSelected" ref="ossManage" />
    </Modal>
    <!-- 审核模态框 -->
    <Modal v-model="applyFlag" @on-cancel="close">
      <p slot="header" style="color: #f60; text-align: center">
        <Icon type="ios-information-circle"></Icon>
        <span>{{applyTitle}}</span>
      </p>
      <div style="text-align: center">
        <p v-show="rejectFlag==false">您确认要审核通过该代理商</p>
        <Form ref="reject" v-show="rejectFlag" :model="reject" :rules="applyRule" label-position="left"
          :label-width="100">
          <FormItem label="驳回理由" prop="valueName">
            <Input type="textarea" v-model="reject.valueName" placeholder="请输入驳回理由"
              :autosize="{minRows: 2,maxRows: 5}"></Input>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="error" @click="audit('REFUSED')">驳回</Button>
        <Button type="info" @click="audit('PASS')">通过</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import region from "@/views/agent-manage/region";
  import * as API_Member from "@/api/agent.js";
  import ossManage from "@/views/sys/oss-manage/ossManage";
  import * as RegExp from "@/libs/RegExp.js";

  export default {
    name: "agent-manage",
    components: {
      region,
      ossManage,
    },
    data() {
      return {
        descTitle: "", // modal标题
        descFlag: false, //编辑查看框
        loading: true, // 表单加载状态
        addFlag: false, // modal显隐控制
        updateRegion: false, // 地区
        addMemberForm: {
          // 添加用户表单
          mobile: "",
          username: "",
          password: "",
        },
        searchForm: {
          // 请求参数
          pageNumber: 1,
          pageSize: 10,
          order: "desc",
          username: "",
          mobile: "",
          disabled: "OPEN",
        },
        picModelFlag: false, // 选择图片
        form: {
          region: '',
          regionId: ''
        }, // 表单数据
        addRule: {
          // 验证规则
          mobile: [{
              required: true,
              message: "请输入手机号码"
            },
            {
              pattern: RegExp.mobile,
              message: "请输入正确的手机号",
            },
          ],
          username: [{
            required: true,
            message: "请输入会员名称"
          }],
          password: [{
            required: true,
            message: "请输入密码"
          }],
        },
        ruleValidate: {}, //修改验证
        columns: [{
            title: "代理商名",
            key: "nickName",
            tooltip: true,
          },
          {
            title: "代理区域",
            key: "partnerRegion",
            tooltip: true,
            width: 400,
            render: (h, params) => {
              return h(
                "div", {
                  style: {
                    display: "flex",
                    justifyContent: "spaceBetween",
                  },
                },
                [
                  h('div', {}, params.row.partnerRegion),
                  h(
                    "Button", {
                      props: {
                        type: "info",
                        size: "small",
                        ghost: true,
                      },
                      style: {
                        marginLeft: "20px",
                        display: this.selectedMember ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.editPerm(params.row);
                        },
                      },
                    },
                    "编辑"
                  ),
                ]
              )
            }
          },
          {
            title: "联系方式",
            key: "mobile",
            render: (h, params) => {
              if (params.row.mobile == null) {
                return h("div", [h("span", {}, "")]);
              } else {
                return h("div", [h("span", {}, params.row.mobile)]);
              }
            },
          },
          {
            title: "发展商家数",
            key: "quantity",
            tooltip: true,
          },
          {
            title: "申请时间",
            key: "createTime",
          },
          {
            title: "状态",
            key: "auditState",
            render: (h, param) => {
              if (param.row.auditState == 'APPLYING') {
                return h("Tag", {
                  props: {
                    color: "geekblue",
                  },
                }, "待审核");
              } else if (param.row.auditState == 'PASS') {
                return h("Tag", {
                  props: {
                    color: "green",
                  },
                }, "通过");
              } else if (param.row.auditState == 'REFUSED') {
                return h("Tag", {
                  props: {
                    color: "red",
                  },
                }, "驳回");
              }
            }
          },

          {
            title: "操作",
            key: "action",
            align: "right",
            fixed: "right",
            render: (h, params) => {
              return h(
                "div", {
                  style: {
                    display: "flex",
                    justifyContent: "center",
                  },
                },
                [
                  h(
                    "Button", {
                      props: {
                        type: "success",
                        size: "small",
                      },
                      style: {
                        marginRight: "5px",
                        display: params.row.auditState != 'APPLYING' ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.apply(params.row);
                        },
                      },
                    },
                    "审核"
                  ),
                  h(
                    "Button", {
                      props: {
                        type: "info",
                        size: "small",
                      },
                      style: {
                        marginRight: "5px",
                        display: this.selectedMember ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.detail(params.row);
                        },
                      },
                    },
                    "查看"
                  ),
                  h(
                    "Button", {
                      props: {
                        size: "small",
                        type: "error",
                      },
                      style: {
                        marginRight: "5px",
                        display: this.selectedMember ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.disabled(params.row);
                        },
                      },
                    },
                    "删除"
                  ),
                ]
              );
            },
          },
        ],
        data: [], // 表单数据
        total: 0, // 表单数据总数
        selectMember: [], //保存选中的用户
        applyFlag: false, //审核框
        applyTitle: '', //审核数据标题
        reject: {
          valueName: ''
        }, //驳回理由绑定输入的数据
        rejectFlag: false, //显示驳回理由多行输入框
        applyRule: {
          // 审核验证规则
          valueName: [{
            required: true,
            message: "请输入驳回理由"
          }]
        },
        dataDetailContent: '', //审核所点击的数据
        userId: '', //用户id
      };
    },
    props: {
      // 是否为选中模式
      selectedMember: {
        type: Boolean,
        default: false,
      },
      // 已选择用户数据
      selectedList: {
        type: null,
        default: () => {
          return [];
        },
      },
    },
    watch: {
      selectedList: {
        handler(val) {
          this.$set(this, "selectMember", JSON.parse(JSON.stringify(val)));
          this.init(this.data);
          // 将父级数据与当前组件数据进行匹配
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
      // 回调给父级
      callback(val, index) {
        this.$set(val, "___selected", !val.___selected);
        console.log(val.___selected);
        console.log(this.selectMember);
        let findUser = this.selectMember.find((item) => {
          return item.id == val.id;
        });
        // 如果没有则添加
        if (!findUser) {
          this.selectMember.push(val);
        } else {
          // 有重复数据就删除
          this.selectMember.map((item, index) => {
            if (item.id == findUser.id) {
              this.selectMember.splice(index, 1);
            }
          });
        }

        this.$emit("callback", val);
      },
      // 初始化信息
      init(data) {
        data.forEach((item) => {
          if (this.selectMember.length != 0) {
            this.selectMember.forEach((member) => {
              if (member.id == item.id) {
                this.$set(item, "___selected", true);
              }
            });
          } else {
            this.$set(item, "___selected", false);
          }
        });
        this.data = data;
      },
      // 分页 改变页码
      changePage(v) {
        this.searchForm.pageNumber = v;
        this.getData();
      },
      // 分页 改变页数
      changePageSize(v) {
        this.searchForm.pageSize = v;
        this.searchForm.pageNumber = 1;
        this.getData();
      },
      // 搜索
      handleSearch() {
        this.searchForm.pageNumber = 1;
        this.searchForm.pageSize = 10;
        this.getData();
      },
      // 审核
      apply(row) {
        console.log(row)
        let that = this;
        that.dataDetailContent = row
        that.applyFlag = true
        that.applyTitle = '审核' + row.nickName + '代理'
      },
      // 审核弹框点击关闭按钮清空操作的数据
      close() {
        let that = this;
        that.applyFlag = false
        that.rejectFlag = false
        that.reject.valueName = ''
      },
      // 驳回/通过
      audit(operation) {
        let that = this;
        // 驳回状态
        if (operation == 'REFUSED') {
          that.rejectFlag = true
          this.$refs.reject.validate((valid) => {
            if (valid) {
              console.log('驳回理由输入的数据' + that.reject.valueName)
              console.log(that.dataDetailContent)
              let param = {
                id: that.dataDetailContent.id,
                auditState: 'REFUSED',
                auditRemark: that.reject.valueName
              }
              API_Member.applyData(param).then((res) => {
                if (res.code == 200) {
                  // // 再次调用驳回接口
                  this.$Message.success('驳回成功');
                  that.applyFlag = false
                  that.rejectFlag = false
                  that.reject.valueName = ''
                  that.getData()
                }
              });

            }
          })
        } else {
          let param = {
            id: that.dataDetailContent.id,
            auditState: 'PASS',
          }
          API_Member.applyData(param).then((res) => {
            if (res.code == 200) {
              this.$Message.success('审核通过');
              that.applyFlag = false
              that.rejectFlag = false
              that.reject.valueName = ''
              that.getData()
            }
          });
        }

      },
      //查看详情修改
      editPerm(val) {
        this.descTitle = `查看用户 ${val.nickName}`;
        this.descFlag = true;
        this.updateRegion = false;
        this.getMemberInfo(val);
      },
      addMember() {
        this.addFlag = true;
        this.$refs.addMemberForm.resetFields();
      },
      /**
       * 查询查看会员详情
       */
      getMemberInfo(val) {
        let that = this;
        that.form.region = val.region;
        that.form.regionId = val.regionId;
        that.userId = val.id;
      },

      //查询会员列表
      getData() {
        API_Member.getMemberListData(this.searchForm).then((res) => {
          if (res.result.records) {
            this.loading = false;
            this.init(res.result.records);
            this.total = res.result.total;
          }
        });
      },
      // 选中的图片
      callbackSelected(val) {
        this.picModelFlag = false;
        this.form.face = val.url;
      },
      //添加会员提交
      addMemberSubmit() {
        console.log(123)
        this.addMemberForm.password = this.md5(this.addMemberForm.password);
        this.$refs.addMemberForm.validate((valid) => {
          if (valid) {
            API_Member.addMember(this.addMemberForm).then((res) => {
              if (res.result) {
                this.$refs.addMemberForm.resetFields();
                this.getData();
                this.$Message.success("添加成功！");
                this.addFlag = false;
              }
            });
          }
        });
      },

      // 选中的地址
      selectedRegion(val) {
        this.region = val[1];
        this.regionId = val[0];
      },
      //查看会员
      detail(row) {
        this.$router.push({
          name: "agent-detail",
          query: {
            id: row.id
          }
        });
      },

      //删除会员
      disabled(v) {
        this.$Modal.confirm({
          title: "提示",
          content: "<p>确认删除此会员？</p>",
          onOk: () => {
            API_Member.deleteAgent(v.id).then((res) => {
              if (res.success) {
                this.$Message.success("删除成功");
                this.getData();
              } else {
                // this.$Message.error(res.message);
              }
            });
          },
        });
      },

      // 提交修改数据
      handleSubmitModal() {
        let that = this;
        let submit = {
          regionId: that.form.regionId,
          region: that.form.region,
          id: that.userId
        };
        if (that.region != "undefined") {
          submit.regionId = that.regionId;
          submit.region = that.region;
        }
        API_Member.updateMember(submit).then((res) => {
          if (res.code == 200) {
            that.$Message.success("修改成功！");
            that.getData();
          } else {
            that.$Message.error('修改失败！')
          }
        });
      },
    },
    mounted() {
      this.getData();
    },
  };
</script>
<style lang="scss" scoped>
  /deep/ .ivu-table-wrapper {
    width: 100%;
  }

  /deep/ .ivu-card {
    width: 100%;
  }

  .face {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
</style>
